var models = require ('../db');
var express = require ('express');
var router = express.Router ();
var mysql = require ('mysql');
const $sql = require ('../sqlMap');
const fs = require ('fs');
const fileRoot = 'upload/';
var isexist = fs.existsSync (fileRoot);
if (!isexist) {
  fs.mkdirSync (fileRoot);
}
var conn = mysql.createConnection (models.mysql);
conn.connect ();
var query = function (sql, param, callback) {
  conn.beginTransaction (function (err) {
    if (err) {
      console.err ('begin transaction failed');
    }
    conn.query (sql, param, function (err, result) {
      if (err) {
        conn.rollback (() => {
          console.log ('transaction rollback');
        });
      }
      callback (err, result);
      console.log ('rw success');
    });
  });
};

router.post ('/add', (req, res) => {
  var sql = $sql.file.add;
  var param = req.body;
  var fd = fs.openSync (fileRoot + param.title + '.txt', 'w');
  fs.writeSync (fd, param.content);
  fs.closeSync (fd);

  query (sql, [param.title, fileRoot + param.title + '.txt'], function (
    err,
    result
  ) {
    if (err) {
      console.log (err);
    }
    if (result) {
      jsonWrite (res, result);
    }
  });
});

router.post ('/list', (req, res) => {
  var sql = $sql.file.list;
  query (sql, [], function (err, result) {
    if (err) {
      console.log (err);
    }
    if (result) {
      jsonWrite (res, result);
    }
  });
});

router.post ('/find', (req, res) => {
  var sql = $sql.file.selectById;
  var param = req.body;
  query (sql, [param.id], function (err, result) {
    if (err) {
      console.log (err);
    }
    if (result) {
      var dataString = JSON.stringify (result);
      var dts = JSON.parse (dataString);
      fs.readFile (fileRoot + dts[0].title + '.txt', 'utf-8', function (
        err,
        data
      ) {
        if (!err) {
          dts[0].content = data.toString ();
        }
        jsonWrite (res, dts);
      });
    }
  });
});

router.post ('/edit', (req, res) => {
  var sql = $sql.file.edit;
  var param = req.body;
  console.log (param);

  var fd = fs.openSync (fileRoot + param.title + '.txt', 'w');
  fs.writeSync (fd, param.content);
  fs.closeSync (fd);

  query (
    sql,
    [param.title, fileRoot + param.title + '.txt', param.id],
    function (err, result) {
      if (err) {
        console.log (err);
      }
      if (result) {
        jsonWrite (res, result);
      }
    }
  );
});

router.get ('/download', function (req, res, next) {
  console.log (req.query);
  let filename = req.query.file;
  res.download (filename);
});

router.post ('/lock', (req, res) => {
  var sql = $sql.file.lock;
  var param = req.body;
  console.log (param);
  query (sql, [param.id], function (err, result) {
    if (err) {
      console.log (err);
    }
    if (result) {
      jsonWrite (res, result);
    }
  });
});

router.post ('/unlock', (req, res) => {
  var sql = $sql.file.unlock;
  var param = req.body;
  console.log (param);
  query (sql, [param.id], function (err, result) {
    if (err) {
      console.log (err);
    }
    if (result) {
      jsonWrite (res, result);
    }
  });
});

var jsonWrite = function (res, ret) {
  if (typeof ret === 'undefined') {
    res.json ({
      code: '1',
      msg: 'operator failed',
    });
  } else {
    res.json (ret);
  }
};

module.exports = router;
